package com.anhua.config;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

//@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ControllerAdvice
public class MyExcetionConfig {
    @ExceptionHandler(value = MyExcetion.class)
    @ResponseBody
    public String myexcetion(Exception e, HttpServletRequest request){
        if (e instanceof MyExcetion){
            MyExcetion myExcetion= (MyExcetion) e;
            String message = myExcetion.getMessage();
            return message;
        }
        else if(e instanceof BindException){
            BindException bindException= (BindException) e;
            FieldError fieldError= bindException.getBindingResult().getFieldError();
            return fieldError.getDefaultMessage();
        }
else {
            return e.getMessage();
        }
    }


}
